#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include <sys/time.h>
 
#include "data_type.h"
#include "cube.h"
#include "cube_define.h"
#include "cube_record.h"

#include "score_compute.h"
#include "flag_verify.h"

#include "flag_output.h"
// add para lib_include

char Buf[DIGEST_SIZE*4];

static time_t max_time=2;

int flag_output_init(void * sub_proc, void * para)
{
	int ret;

	return 0;
}

int flag_output_start(void * sub_proc, void * para)
{
	int ret;
	void * recv_msg;
	int type;
	int subtype;
	// add yorself's module exec func here
	while(1)
	{
		usleep(time_val.tv_usec);

		ret=ex_module_recvmsg(sub_proc,&recv_msg);
		if(ret<0)
			continue;
		if(recv_msg==NULL)
			continue;
		type=message_get_type(recv_msg);
		subtype=message_get_subtype(recv_msg);
		if(!memdb_find_recordtype(type,subtype))
		{
			printf("message format (%d %d) is not registered!\n",
			message_get_type(recv_msg),message_get_subtype(recv_msg));
			continue;
		}
	   	if((type==TYPE(FLAG_VERIFY))&&(subtype==SUBTYPE(FLAG_VERIFY,SCORE)))
		{
			ret=proc_flag_output(sub_proc,recv_msg);
		}
	}
	return 0;
}

int proc_flag_output(void * sub_proc,void * recv_msg)
{
	int ret;
	RECORD(FLAG_VERIFY,FLAG) * flag_info;
	RECORD(FLAG_VERIFY,SCORE) * flag_score;
	RECORD(GENERAL_RETURN,STRING) * flag_output;
	void * new_msg;
	int output_num=0;

    	flag_info = message_get_record(recv_msg,&flag_score,0);
    DB_RECORD * db_record;

    db_record=memdb_get_first(TYPE_PAIR(FLAG_VERIFY,FLAG));

    sleep(2);
    while(db_record!=NULL)
    {
        flag_info=db_record->record;
        if(flag_info!=NULL)
        {
            if(flag_info->score <= flag_score->score)
            {
                flag_output=Talloc0(sizeof(*flag_output));
                if(flag_output==NULL)
                    return -ENOMEM;
                flag_output->name = dup_str(flag_score->name,DIGEST_SIZE);
                flag_output->return_value=dup_str(flag_info->flag,0);
                new_msg=message_create(TYPE_PAIR(GENERAL_RETURN,STRING),recv_msg);
                if(new_msg==NULL)
                    return -EINVAL;
                message_add_record(new_msg,flag_output);
                ex_module_sendmsg(sub_proc,new_msg);
		output_num++;
            }
        }
        db_record=memdb_get_next(TYPE_PAIR(FLAG_VERIFY,FLAG));
    }
    if(output_num == 0)
    {
                flag_output=Talloc0(sizeof(*flag_output));
                if(flag_output==NULL)
                    return -ENOMEM;
                flag_output->name = dup_str(flag_score->name,DIGEST_SIZE);
                flag_output->return_value=dup_str("no flag output",0);
                new_msg=message_create(TYPE_PAIR(GENERAL_RETURN,STRING),recv_msg);
                if(new_msg==NULL)
                    return -EINVAL;
                message_add_record(new_msg,flag_output);
                ex_module_sendmsg(sub_proc,new_msg);

    }
	return 0;
}
